Ext.extend(app.module,{
    currentFormValues: {},
    init: function(){
        this.render();
        this.body = new Ext.Panel({
            layout: 'border',
            items:[this.tree,this.grid]
        });
        this.main.add(this.body);
        this.main.doLayout();
        //初始化加载
        this.ds.load( {
            params : {
                start : 0,
                limit : 20
            }
        });
    },
    //创建表格
    creatGrid: function(){
        var main = this;    //设置main=this，方便子组件里取值，因子组件的this可能不为现在这个了
        main.ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'dept/depts.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'},
                {name:'description'},
                {name:'parentid'},
                {name:'parentname'}
            ])
        });
        // 翻页排序时带上查询条件
        main.ds.on('beforeload', function() {
            this.baseParams = {
                queryParam: Ext.getCmp('queryParam').getValue()
            };
        });
        main.sm = new Ext.grid.CheckboxSelectionModel();    //设置多选框
        var pagesize_combo = new Ext.form.ComboBox( {       //设置分页栏的每页记录数选择
            name : 'pagesize',
            hiddenName : 'pagesize',
            typeAhead : true,
            triggerAction : 'all',
            lazyRender : true,
            mode : 'local',
            store : new Ext.data.ArrayStore(
                {
                    fields : [ 'value', 'text' ],
                    data : [ [ 10, '10条/页' ], [ 20, '20条/页' ],
                        [ 50, '50条/页' ], [ 100, '100条/页' ],
                        [ 250, '250条/页' ], [ 500, '500条/页' ] ]
                }),
            valueField : 'value',
            displayField : 'text',
            value : '20',
            editable : false,
            width : 85
        });
        var number = parseInt(pagesize_combo.getValue());

        pagesize_combo.on("select", function(comboBox) {
            var bbar = Ext.getCmp('deptbbar');
            bbar.pageSize = parseInt(comboBox.getValue());
            number = parseInt(comboBox.getValue());
            main.ds.reload( {
                params : {
                    start : 0,
                    limit : bbar.pageSize
                }
            });
        });
        var grid = new Ext.grid.GridPanel({
            store: main.ds,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            sm: main.sm,
            columns: [
                new Ext.grid.RowNumberer(),
                main.sm,
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'id',
                    header: '部门编号'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'name',
                    header: '部门名称'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'description',
                    header: '部门描述'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'parentid',
                    header: '上级部门编号'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'parentname',
                    header: '上级部门名称',
                    renderer: function(value,metadata,record,rowIndex,colIndex,store){  //设置该列显示的值
                        var parentid = record.get("parentid");
                        if(parentid==0 || parentid=='0'){
                            return '';
                        } else {
                            return main.tree.getNodeById(parentid).text;
                        }

                    }
                }
            ],
            tbar: {
                xtype: 'toolbar',
                items: [
                    {
                        text: '新增',
                        iconCls : 'btn-new',
                        scope: this,
                        handler: this.add
                    },
                    '-',
                    {
                        text: '修改',
                        iconCls : 'btn-edit',
                        scope: this,
                        handler: this.edit
                    },
                    '-',
                    {
                        text: '删除',
                        iconCls : 'btn-del',
                        scope: this,
                        handler: this.del
                    },
                    '->',
                    {
                        xtype: 'textfield',
                        id : 'queryParam',
                        name : 'queryParam',
                        emptyText : '请输入部门名称',
                        enableKeyEvents : true,
                        listeners : {
                            specialkey : function(field, e) {
                                if (e.getKey() == Ext.EventObject.ENTER) {
                                    main.ds.load( {
                                        params : {
                                            start : 0,
                                            limit : Ext.getCmp('deptbbar').pageSize,
                                            queryParam : Ext.getCmp('queryParam').getValue()
                                        }
                                    });
                                }
                            }
                        },
                        width : 130
                    },
                    {
                        text : '查询',
                        iconCls : 'btn-search',
                        handler : function() {
                            main.ds.load( {
                                params : {
                                    start : 0,
                                    limit : Ext.getCmp('deptbbar').pageSize,
                                    queryParam : Ext.getCmp('queryParam').getValue()
                                }
                            });
                        }
                    }
                ]
            },
            bbar: {
                id: 'deptbbar',
                xtype: 'paging',
                pageSize : number,
                store : main.ds,
                displayInfo : true,
                displayMsg : '显示{0}条到{1}条,共{2}条',
                emptyMsg : "没有符合条件的记录",
                items : [ '-', '&nbsp;&nbsp;', pagesize_combo ]
            }
        });
        return grid;
    },
    //创建树
    creatTree: function(){
        this.loader = new Ext.tree.TreeLoader({dataUrl:'dept/getDeptTree.do'});
        this.loader.processResponse = function(response, node, callback){
            var json = response.responseText;
            try{
                var json = eval("(" + json + ")");
                node.beginUpdate();
                var o = json["key"];
                for(var i=0,len=o.length; i<len; i++){
                    var n = this.createNode(o[i]);
                    if(n){
                        node.appendChild(n);
                    }
                }
                node.endUpdate();
                if(typeof callback == "function"){
                    callback(this,node);
                }
            } catch(e) {
                this.handleFailure(response);
            }
        }
        var tree = new Ext.tree.TreePanel({
            id: 'treeDept',
            width: 200,
            collapsible: true,
            lines:false,   // 去掉树的线
            title: '部门管理',
            region: 'west',
            split: true,
            root: {
                id: 0,
                text: '根节点',
                expanded: true
            },
            rootVisible : false,// 根节点是否可见
            loader: this.loader
        });
        return tree;
    },
    //创建窗口，用于增加、删除
    getDialog: function(){
        this.form = this.getForm();
        var dlg = new Ext.Window({
            height: 200,
            width: 400,
            layout: 'fit',
            border: false,
            frame: true,
            title: '',
            modal: true,
            plain: true,
            resizable: false,
            items: [this.form],
            listeners: {
                scope: this,
                render: function(fp){
                    this.form.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.form.getForm();
                    f.setValues(this.currentFormValues);
                    f.clearInvalid();
                }
            }
        });
        return dlg;
    },
    getForm: function() {
        var main = this;
        addDeptTree = new Ext.tree.TreePanel( {
            loader: main.loader,
            root : {
                id: 0,
                text: '根节点',
                expanded: true
            },
            autoScroll : true,
            rootVisible : false,// 根节点是否可见
            animate : false,    // 展开,收缩动画
            useArrows : false,  // 是否使用箭头样式
            lines:false,        // 去掉树的线
            border : false
        });
        // 监听下拉树的节点单击事件
        addDeptTree.on('click', function(node) {
            main.comboxWithTree.setValue(node.text);
            Ext.getCmp('parentid').setValue(node.id);
            main.comboxWithTree.collapse();
        });
        this.comboxWithTree = new Ext.form.ComboBox({
            id : 'parentdeptname',
            store : new Ext.data.SimpleStore( {
                fields: [],
                data: [[]]
            }),
            editable: false,
            value : ' ',
            emptyText : '请选择...',
            fieldLabel : '上级部门',
            anchor : '100%',
            mode : 'local',
            triggerAction : 'all',
            maxHeight : 390,
            // 下拉框的显示模板,addDeptTreeDiv作为显示下拉树的容器
            tpl : "<tpl for='.'><div style='height:390px'><div id='addDeptTreeDiv'></div></div></tpl>",
            allowBlank : false,
            onSelect : Ext.emptyFn
        });
        // 监听下拉框的下拉展开事件
        this.comboxWithTree.on('expand', function() {
            if(Ext.getCmp('parentid').getValue()!='0'){
                // 将树挂到treeDiv容器
                addDeptTree.render('addDeptTreeDiv');
                addDeptTree.root.reload(); // 每次下拉都会加载数据
            } else {
                Ext.Msg.alert("提示","根节点不允许指定上级部门");
            }
        });
        var form = new Ext.form.FormPanel({
            id: 'addDeptFormPanel',
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'dept/save.do',
            labelWidth: 80,
            defaults: {
                anchor: '90%'
            },
            items: [
                {
                    xtype: 'hidden',
                    name: 'id',
                    fieldLabel: 'Label'
                },
                {
                    xtype: 'textfield',
                    name: 'name',
                    allowBlank: false,
                    emptyText: '部门名称不能为空',
                    fieldLabel: '部门名称'
                },
                this.comboxWithTree,
                {
                    xtype: 'textarea',
                    name: 'description',
                    fieldLabel: '描述'
                },
                {
                    id : 'parentid',
                    xtype: 'textarea',
                    name : 'parentid',
                    hidden : true
                }
            ],
            buttons: [{
                text: '确定',
                scope: this,
                handler: function() {
                    this.submit();
                }
            },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
        });
        return form;
    },
    submit: function(){
        if (this.form.getForm().isValid()) {
            var id = this.form.getForm().findField("id").getValue();
            this.form.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: '',
                submitEmptyText: false,     //禁止提交emptyText
                success: function(form, action) {
                    var info = action.result.info;
                    if (action.result.success) {
                        this.ds.reload();
                        this.tree.root.reload();
                        if (action.result.method == "Create") {
                            this.form.getForm().reset();
                        } else {
                            this.dlg.hide();
                        }
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    add: function() {
        this.dlg = this.getDialog();
        Ext.apply(this.currentFormValues, {
            id: '',
            name: '',
            description: '',
            parentid: ''
        });
        this.comboxWithTree.setValue('');
        this.dlg.setTitle("增加部门");
        this.dlg.show();
    },

    edit: function() {
        this.dlg = this.getDialog();
        var recs = this.grid.getSelectionModel().getSelections();
        if (recs.length==0) {
            Ext.Msg.alert('信息', '请选择要编辑的部门。');
        } else if(recs.length>1) {
            Ext.Msg.alert('信息', '只能选择一个部门进行编辑。');
        } else {
            this.dlg.setTitle("编辑部门");
            Ext.apply(this.currentFormValues, {
                id: recs[0].data.id,
                name: recs[0].data.name,
                description: recs[0].data.description,
                parentid: recs[0].data.parentid
            });
            if(recs[0].data.parentid==0){
                this.comboxWithTree.setValue('无上级部门...');
            } else {
                this.comboxWithTree.setValue(this.ds.getById(recs[0].data.parentid).get('name'));
            }
            this.dlg.show();
        }
    },

    del: function() {
        var main = this;
        if (this.grid.getSelectionModel().hasSelection()) {
            var recs = this.grid.getSelectionModel().getSelections();
            var ids = [];
            var titles = [];
            for (var i = 0; i < recs.length; i++) {
                var data = recs[i].data;
                if(data.parentid!=0){
                    ids.push(data.id);
                    titles.push(data.name);
                    //删除节点将删除所有子节点
                    var nodes = main.tree.getNodeById(data.id).childNodes;
                    for(var j=0;j<nodes.length;j++){
                        ids.push(nodes[j].id);
                        titles.push(nodes[j].text);
                    }
                } else {
                    Ext.Msg.alert("提示","根节点不能删除！");
                    return;
                }
            }
            //去掉重复
            ids = main.distinct(ids);
            titles = main.distinct(titles);
            Ext.Msg.confirm('删除部门', '确定删除以下部门？<br><font color="red">' + titles.toString() + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        Ext.Ajax.request({
                            method:'post',
                            url:'dept/remove.do',
                            params:{
                                ids:ids.toString()
                            },
                            scope: main,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                if(result.success=='true') {
                                    main.ds.reload();
                                    main.tree.root.reload();
                                    Ext.Msg.alert('信息', info);
                                }else {
                                    Ext.Msg.alert('信息', info);
                                }
                            },
                            failure: function(resp,opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                Ext.Msg.alert('提示', info);
                            }
                        });
                    }
                });
        } else {
            Ext.Msg.alert('信息', '请选择要删除的部门！');
        }
    },
    render: function() {
        if (!this.tree) {
            this.tree = this.creatTree();
        }
        if (!this.grid) {
            this.grid = this.creatGrid();
        }
    },
    distinct: function(arr){    //去掉重复
        var self = arr;
        var _a = arr.concat().sort();
        _a.sort(function(a,b){
            if(a == b){
                var n = self.indexOf(a);
                self.splice(n,1);
            }
        });
        return self;
    }
});